import { Stack } from "expo-router";
import { getHeaderStyle } from "@/styles/header.style";
import { useTheme } from "@/contexts/ThemeContext";
import {
  View,
  Text,
  FlatList,
  Image,
  TouchableOpacity,
  RefreshControl,
  Alert,
} from "react-native";
import React, { useEffect, useState, useCallback } from "react";
import { LoginHistory } from "@/types/login-history";
import {
  getLoginHistory,
  deleteLoginHistory,
  clearLoginHistory,
} from "@/services/api/login-history";
import { ResponseCode } from "@/types/api-common";
import {
  convertDateStringToBeijingTime,
  convertToTodayTime,
  convertUTCStringToBeijingTime,
} from "@/utils/time-utils";
import { getDeviceTypeImage, getDeviceTypeLabel } from "@/utils/device-utils";
import styles from "./login-history.style";
import { Feather, Ionicons, MaterialIcons } from "@expo/vector-icons";
import Swipeable from "@/components/Global/Swipeable";
export default function LoginHistoryPage() {
  const { themeMode } = useTheme();
  const headerStyles = getHeaderStyle(themeMode);

  const [loginHistory, setLoginHistory] = useState<LoginHistory[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const fetchLoginHistory = async () => {
    const response = await getLoginHistory();
    if (response.data.code === ResponseCode.SUCCESS) {
      setLoginHistory(response.data.data);
    } else {
      console.error("获取登录历史失败:", response.data.message);
    }
  };

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await fetchLoginHistory();
    setRefreshing(false);
  }, []);

  const showDeleteConfirm = (id: number) => {
    Alert.alert("删除记录", "是否删除该条登录记录？", [
      { text: "取消", style: "cancel" },
      {
        text: "删除",
        onPress: async () => {
          const resp = await deleteLoginHistory(id);
          if (resp.data.code === ResponseCode.SUCCESS) {
            setLoginHistory((prev) => prev.filter((item) => item.id !== id));
          }
        },
        style: "destructive",
      },
    ]);
  };

  const handleClearAll = () => {
    Alert.alert("清空所有记录", "确定要清空所有登录历史吗？", [
      { text: "取消", style: "cancel" },
      {
        text: "清空",
        onPress: async () => {
          const res = await clearLoginHistory();
          if (res.data.code === ResponseCode.SUCCESS) {
            setLoginHistory([]);
          }
        },
        style: "destructive",
      },
    ]);
  };

  useEffect(() => {
    fetchLoginHistory();
  }, []);

  const renderItem = ({ item }: { item: LoginHistory }) => (
    <Swipeable>
      <TouchableOpacity
        onLongPress={() => showDeleteConfirm(item.id)}
        delayLongPress={400}
        activeOpacity={0.9}
        style={styles.cardWrapper}
      >
        <View style={styles.card}>
          <View style={styles.cardHeader}>
            <Image
              source={getDeviceTypeImage(item.deviceType)}
              style={styles.deviceIcon}
            />
            <Text style={styles.deviceName}>{item.deviceName}</Text>
          </View>

          <View style={styles.row}>
            <Feather name="monitor" size={16} color="#666" />
            <Text style={styles.infoText}>
              {getDeviceTypeLabel(item.deviceType)}
            </Text>
          </View>

          <View style={styles.row}>
            <MaterialIcons name="access-time" size={16} color="#666" />
            <Text style={styles.infoText}>
              {convertToTodayTime(
                convertDateStringToBeijingTime(item.loginTime)
              )}
            </Text>
          </View>

          <View style={styles.row}>
            <Ionicons
              name={item.status ? "checkmark-circle" : "close-circle"}
              size={16}
              color={item.status ? "green" : "red"}
            />
            <Text style={styles.infoText}>
              登陆{item.status ? "成功" : "失败"}
            </Text>
          </View>

          <View style={styles.row}>
            <Feather name="globe" size={16} color="#666" />
            <Text style={styles.infoText}>{item.ipAddress}</Text>
          </View>

          <View style={styles.row}>
            <Feather name="map-pin" size={16} color="#666" />
            <Text style={styles.infoText}>{item.ipDescription}</Text>
          </View>
        </View>
      </TouchableOpacity>
    </Swipeable>
  );

  return (
    <>
      <Stack.Screen
        options={{
          title: "登录历史",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <View style={{ flex: 1 }}>
        <FlatList
          data={loginHistory}
          keyExtractor={(item) => item.id.toString()}
          renderItem={renderItem}
          contentContainerStyle={
            loginHistory.length === 0 && styles.centerEmpty
          }
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          ListEmptyComponent={<Text>暂无登录历史</Text>}
        />

        <View style={[styles.fabContainer]}>
          <TouchableOpacity style={styles.fab} onPress={handleClearAll}>
            <Ionicons name="trash" size={22} color="#fff" />
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
}
